var meterRecordData = [];
var flagDate = undefined;
var deleteFlag = undefined;
var deleteIndex = undefined;
var deleteCount = undefined;
var parentNameData = [];

$(document).ready(function() {
	showLoading();
	$('title', parent.document).html($('title').text());
	setBaseUrl();
	$ajaxList('chargingStation', getChargingStation, {BulidStatus: '3'});
	$ajaxList('searchBalanceInitSetting', getBalanceInitSetting);
	createTableHead("meterRecordThead", meterRecordTable);
	setTimeout(hideLoading, 500);
});
function getBalanceInitSetting(data){
	var balanceInitSettingData = data.balanceInitSettingList[0]
	var balanceStartMonth = balanceInitSettingData && balanceInitSettingData.balanceStartMonth || new Date().getFullYear() + (new Date().getMonth() + 1 < 10 ? "0" + (new Date().getMonth() + 1) : new Date().getMonth() + 1);
	changeYear(0, balanceStartMonth);
	showMonth(getSystemTime().getMonth() + 1);
}
function getChargingStation(data) {
	var length = data.length;
	chargingStationData = data;
	var item = undefined;
	for (var i = 0; i < length; i++) {
		$("#chargingStationID").append("<option value='" + data[i].chargingStationID + "'>" + data[i].chargingStationName + "</option>");
		item = {};
		item.ID = data[i].chargingStationID;
		item.label = data[i].chargingStationName;
		item.value = data[i].chargingStationName;
		parentNameData.push(item);
	}
	$(function(){
		autoComplete("name", parentNameData, '', "chargingStationID");
		bindInput("name", onInput);  
	});
}
function onInput(){
	$("#chargingStationID").val('');
}
function getChargingStationID(){
	var value = $("#name").val();
	if (!value) {
		$("#chargingStationID").val('');
	} else {
		if (!$("#chargingStationID").val() && parentNameData && parentNameData.length > 0) {
			var matcherData = filter(parentNameData, value);
			if (matcherData) {
				var length = matcherData.length;
				for (var i=0; i<length; i++) {
					if (matcherData[i] && matcherData[i].value == value) {
						$("#chargingStationID").val(matcherData[i].ID);
						break;
					}
				}
			}
		}
	}
}
function showMonth(index){
	$('.activeMonthLi').removeClass("activeMonthLi");
	$("#li"+ index).addClass("activeMonthLi");
	var year = $("#showYear").html().replace(/[^0-9]/ig,"");
	index = index >= 10 ? index : "0" + index;
	$("#meterDate").val(year + index);
	$("#chargingStationID").val('');
	search();
}

function search() {
	$("#errorMessage").hide();
	$("#errorMessage").empty();
	$ajax('searchMeterRecord', 'checkMeterSearch', searchMeterRecord);
}
function searchMeterRecord(data){
	meterRecordData = data && data.meterRecordList || [];
	var meterRecordTbody = $("#meterRecordTbody");
	meterRecordTbody.empty();
	var length = meterRecordData.length;
	if (length == 0) {
		$("#meterRecordThead").hide();
		$("#errorMessage").show();
		$("#errorMessage").html(messageContent["Balance.BalanceMeterRecordNotExist"]);
		return;
	}
	$("#meterRecordThead").show();
	var chargingStationID = undefined;
	var addMeterRecordDTTM = undefined;
	var rowspanCount = undefined;
	for(var i=0; i<length + 1; i++){
		if (i == length || chargingStationID != meterRecordData[i].chargingStationID || addMeterRecordDTTM != meterRecordData[i].addMeterRecordDTTM) {
			chargingStationID = meterRecordData[i] && meterRecordData[i].chargingStationID;
			addMeterRecordDTTM = meterRecordData[i] && meterRecordData[i].addMeterRecordDTTM;
			if (rowspanCount) {
				for (var j=i - rowspanCount; j<i; j++) {
					$tr = $('<tr>').appendTo(meterRecordTbody);
					if (j==i - rowspanCount) {
						$('<td rowspan="'+ rowspanCount + '">').html(meterRecordData[i-1].chargingStationName).appendTo($tr);
						$('<td rowspan="'+ rowspanCount + '">').html(timeStamp2String(meterRecordData[i-1].addMeterRecordDTTM)).appendTo($tr);
					}
					$("<td>").html(meterRecordData[j].meterCode).appendTo($tr);
					$("<td>").html(meterRecordData[j].meterRate).appendTo($tr);
					$("<td>").html('<a class="details" onclick="showImg('+meterRecordData[j].id+ ',' +0+ ')">'+meterRecordData[j].meterDate+'</a>').appendTo($tr);
					$("<td>").html('<a class="details" onclick="showImg('+meterRecordData[j].id+ ',' +1+ ')">'+meterRecordData[j].meterTime+'</a>').appendTo($tr);
					$("<td>").html('<a class="details" onclick="showImg('+meterRecordData[j].id+ ',' +3+ ')">'+meterRecordData[j].powerAiguille+'</a>').appendTo($tr);
					$("<td>").html('<a class="details" onclick="showImg('+meterRecordData[j].id+ ',' +4+ ')">'+meterRecordData[j].powerPeak+'</a>').appendTo($tr);
					$("<td>").html('<a class="details" onclick="showImg('+meterRecordData[j].id+ ',' +5+ ')">'+meterRecordData[j].powerFlat+'</a>').appendTo($tr);
					$("<td>").html('<a class="details" onclick="showImg('+meterRecordData[j].id+ ',' +6+ ')">'+meterRecordData[j].powerGrain+'</a>').appendTo($tr);
					$("<td>").html('<a class="details" onclick="showImg('+meterRecordData[j].id+ ',' +2+ ')">'+meterRecordData[j].powerTotal+'</a>').appendTo($tr);
					$("<td>").html('<a class="details" onclick="showImg('+meterRecordData[j].id+ ',' +7+ ')">'+meterRecordData[j].idleTotal+'</a>').appendTo($tr);
					if (j==i - rowspanCount) {
						$('<td rowspan="'+ rowspanCount + '">').html(
					        '<span onclick="chkBefore('+ j +',\'update\')"' + 
					            'class="bacHoverBlue details operationWord">修改</span>' +
					        '<span onclick="chkBefore('+ j +',\'delete\', '+rowspanCount+')"' +
					            'class="bacHoverRed details operationWord">删除</span>').appendTo($tr);
					}
				}
			}
			rowspanCount = 1;
		} else {
			rowspanCount++;
		}
	}
	setTimeout(hideLoading, 500);
}
function accMul(arg1,arg2) {
	var m=0,s1=arg1.toString(),s2=arg2.toString();
	try {
		m+=s1.split(".")[1].length
	} catch(e){
	}
	try {
		m+=s2.split(".")[1].length
	} catch(e){
	}
	return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
}
function chkBefore(index, chkFlag, count){
	if (chkFlag == "update") {
		update(index);
	} else if(chkFlag == "delete") {
		deleteIndex = index;
		deleteCount = count;
		deleteFlag = "delete"
		showMessge(messageContent["Delete.Confirm"], "model2");
	}
}
function update(index){
	window.parent.detalisSkip('costManage/meterRecordUpdate');
	$("#parentSkipMenu", parent.document).val("costManagePage");
	$("#chargingStationID", parent.document).val(meterRecordData[index].chargingStationID);
	$("#detailID", parent.document).val(meterRecordData[index].meterDate);
}
function getUrl(){
	if(deleteFlag == "update"){
		return "updateMeterRecord";
	} else if(deleteFlag == "delete"){
		return "deleteMeterRecord";
	}
}
function getDeleteDataList(data, ID){
	var dataList = [];
	for (var i=0; i<deleteCount; i++) {
		dataList.push(data && data[deleteIndex + i] && data[deleteIndex + i].id);
	}
	return dataList.toString();
}
function getData(){
	return {id: getDeleteDataList(meterRecordData, "id"), chargingStationID: meterRecordData[deleteIndex].chargingStationID, addMeterRecordDate: timeStamp2String(meterRecordData[deleteIndex].addMeterRecordDTTM)};
}
function sure(data){
	var result = data && data.result;
	if (result == "Success") {
		showMessge(messageContent["Delete.Success"]);
	} else if (result == "NotFound") {
		showMessge(messageContent["Delete.NotFound"]);
	} else {
		showMessge(messageContent["Delete.Error"]);
	}
	search();
}
function showImg(meterRecordID, index){
	for(var i = 0; i < meterRecordData.length; i++){
		if(meterRecordData[i].id == meterRecordID){
			$("#meterImg").html('<img style="width:736px;height:420px" src="getMeterRecordImg?meterCode=' + meterRecordData[i].meterCode + '&meterType=' + index + '&meterTime=' + timeStamp2String(meterRecordData[i].addMeterRecordDTTM) + '&chargingStationID=' + meterRecordData[i].chargingStationID + '" onLoad="foundImg();" onerror="notFoundImg();">');
			break;
		}
	}
}
function foundImg(){
	$("#showImg").modal("show");
}
function notFoundImg(){
	showMessge("该图片不存在,请通过【修改】操作上传图片!");
}
function importFile() {
	$("#importForm").empty();
	$("#importForm").append(
		'<div class="form-group">'+
		'<label for="importExcle" class="col-sm-3 control-label">抄表记录文件</label>' + 
		'<div class="col-sm-8"><input id="importExcle" name="importExcle" type="file" class="form-control"/></div>' + 
		'</div>'
	);
	var option = {
		allowedFileExtensions: ['xls', 'xlsx'],
		showUpload: false,
		previewFileIcon: '<img src="static/images/excel.png" style="width:80px;height:80px;" />',
		showErrorPreview: false
	};
	selectFile("importExcle", option);
	$("#importFileModal").modal("show");
}
function sureImport() {
	var importExcle = $("#importExcle").val();
	if (!importExcle) {
		$("#importFile").tips({
			side : 2,
			msg : '请选择要上传的抄表文件',
			bg : '#AE81FF',
			time : 3
		});
		$("#importFile").focus();
	} else {
		showLoading();
		$ajaxSubmit('importForm', 'importMeterRecord', importFileResult);
	}
}
function importFileResult(data) {
	setTimeout(hideLoading, 500);
	$("#importFileModal").modal("hide");
	var result = data && data.result;
	if (result == "Success") {
		var message = "导入成功";
		var count = data && data.count || 0;
		if (count > 0) {
			message = message + ", 其中有" + count + "条重复数据被更新";
		}
		showMessge(message + "！");
	} else if (result == "JsonError") {
		showMessge("导入失败，导入的JSON模板错误 或 不存在！");
	} else if (result == "NotFound") {
		showMessge("导入失败，文件不存在 或 文件内没有数据!");
	} else {
		showMessge("导入异常，请重新选择文件 或 联系管理员！");
	}
}